//
//  NetworkBaseAPI.m
//  SLDemo
//
//  Created by bocai on 2016/12/5.
//  Copyright © 2016年 Heracles. All rights reserved.
//

#import "NetworkBaseAPI.h"
#import "NetworkSessionManager.h"

@implementation NetworkBaseAPI

- (instancetype)init
{
    if (self = [super init]) {
        self.encodeMethod = kDefaultEncodeMethod;
        self.decodeMethod = kDefaultDecodeMethod;
        self.version = kDefaultVersion;
        self.commonParameters = kDefaultCommonParameters;
    }
    return self;
}

+ (instancetype)apiWithURLString:(NSString *)urlString
                      httpMethod:(NetworkHTTPMethod)httpMethod
                      parameters:(NSDictionary *)parameters
{
    NetworkBaseAPI *api = [self new];
    api.urlString = urlString;
    api.httpMethod = httpMethod;
    api.parameters = parameters;
    return api;
}

- (void)request
{
    [[NetworkSessionManager sharedManager] requestWithAPI:self callbackBlock:^(NetworkResponseModel *responseModel, NSProgress *progress, NSError *error) {
        if (_delegate) {
            if ([_delegate respondsToSelector:@selector(requestProgressWithAPI:)] && progress) {
                _progress = progress;
                [_delegate requestProgressWithAPI:self];
            }
            if ([_delegate respondsToSelector:@selector(requestFinishedWithAPI:)] && (responseModel || error)) {
                _responseModel = responseModel;
                _error = error;
                [_delegate requestFinishedWithAPI:self];
            }
        }
    }];
}

- (void)requestWithDelegate:(id<NetworkAPIDelegate>)delegate
{
    _delegate = delegate;
    [self request];
}

- (NSString *)transformURLString
{
    if (!self.version || [self.version isEqualToString:@""]) {
        return self.urlString;
    }
    return [NSString stringWithFormat:@"%@/%@", self.version, self.urlString];
}

- (NSDictionary *)transformParameters
{
    if (!self.commonParameters) {
        return self.parameters;
    }
    NSMutableDictionary *parameters = [self.parameters mutableCopy];
    [parameters addEntriesFromDictionary:self.commonParameters];
    return [parameters copy];
}

- (NSDictionary *)encodeParameters:(NSDictionary *)parameters
{
    switch (self.encodeMethod) {
        case NetworkEncodeMethodNormal: {
            //
            return nil;
        }
        case NetworkEncodeMethodException: {
            //
            return nil;
        }
    }
}

- (id)decodeResponseObject:(id)responseObject
{
    switch (self.decodeMethod) {
        case NetworkDecodeMethodNormal: {
            //
            return nil;
        }
        case NetworkDecodeMethodException: {
            //
            return nil;
        }
    }
}

@end
